<!--
 * @Author: your name
 * @Date: 2020-06-01 15:23:06
 * @LastEditTime: 2020-06-11 17:30:08
 * @LastEditors: Please set LastEditors
 * @Description: 聊天区域
 * @FilePath: \IM_Web\im_web\src\components\chatRegion\chatRegion.vue
--> 
<template>
    <div class="chat_region">
        <div
            v-if="$store.state.currSessionId === null||userAccount === ''"
            class="flex align_center justify_center logo_box"
        >
            <div class="logo"></div>
        </div>
        <div v-else>
            <div class="chat_region_header">{{chatName}}</div>
            <div class="chat_info" ref="chatInfo">
                <div
                    class="read_more"
                    @click="readMoreHistoryMsgs"
                >{{!noMoreHistoryMsgs?"--- 查看更多 ---":"--- 无更多历史记录 ---"}}</div>
                <!-- <div
                    class="flex chat_item flex_direction justify_between"
                    v-for="(item) in localMsgs"
                    :key="item.idClient"
                >-->
                <ChatItem
                    v-for="(msg) in localMsgs"
                    :key="(msg.idClient || Math.random())"
                    :rawMsg="msg"
                    :userInfos="userInfos"
                    :myInfo="myInfo"
                    @previewImg="imgPreview"
                ></ChatItem>
                <!-- </div> -->
            </div>
            <div class="input_region">
                <div class="emoji_content">
                    <Emoji @add-emoji="addEmoji" @hide-emoji="hideEmoji" v-show="isEmojiShown"></Emoji>
                </div>
                <div class="util flex align_center">
                    <div class="emoji_icon" @click="showEmoji"></div>

                    <div class="files_icon">
                        <input type="file" ref="fileToSent" @change="sendFileMsg" />
                    </div>

                    <!-- <Icon type="ios-happy-outline" style="margin-right:20px;" /> -->
                    <!-- <Icon type="md-folder-open" /> -->
                </div>
                <div class="m_input">
                    <Input
                        v-model.trim="input"
                        type="textarea"
                        :autosize="{minRows: 3, maxRows: 3}"
                        placeholder="Enter something..."
                        style="border:0;"
                        class="m_input_content"
                        @keydown.native="sendMsg($event)"
                    />
                </div>

                <!-- <div class="flex justify_end">
                    <Button type="success" @click="sendMsgDone">发送</Button>
                </div>-->
            </div>
        </div>
        <Modal v-model="imgModel" title footer-hide class-name="vertical-center-modal">
            <div style="background:transparent;" class="flex align_center justify_center">
                <img :src="previewUrl" alt style="max-width:100%;" />
            </div>
            <!-- <div slot="footer"></div> -->
        </Modal>
    </div>
</template>

<script>
import Emoji from "../emoji/ChatEmoji";
import ChatItem from "../chatItem/chatItem";
import tea from "../../utils/TEA.js";
import config from "../../configs";
// Vue.prototype.$tea = tea
export default {
    props: {
        account: {
            type: String,
            default: ""
        },
        sessionId: {
            type: String,
            default: ""
        },
        userInfos: {
            type: Object,
            default() {
                return {};
            }
        },
        myInfo: {
            type: Object,
            default() {
                return {};
            }
        },
        chatName: {
            type: String,
            default: ""
        }
    },
    data() {
        return {
            input: "",
            isStickyOrEnd: true,
            isEmojiShown: false,
            msg: "",
            imgModel: false,
            previewUrl: ""
            // localMsgs: []
            // account: ""
        };
    },
    computed: {
        userAccount: {
            get: function() {
                // this.getTeamMembers()
                return this.account;
            },
            set: function(newVal) {
                console.log(newVal);
            }
        },
        localMsgs() {
            let msgs = this.$store.state.currSessionMsgs;
            this.$nextTick(() => {
                this.stickyOrEnd();
            });

            // 消息去重，问题：发送消息之后切换会话，最后发送的消息可能会出现两次。
            for (var i = 0; i < msgs.length; i++) {
                for (var j = i + 1; j < msgs.length; j++) {
                    if (msgs[i].type !== "timeTag") {
                        if (msgs[i].idClient === msgs[j].idClient) {
                            msgs.splice(j, 1);
                            j--;
                        }
                    } else {
                        if (msgs[i].text === msgs[j].text) {
                            msgs.splice(j, 1);
                            j--;
                        }
                    }
                }
            }
            console.log(msgs);
            // ++this.num;
            return msgs;
        },
        noMoreHistoryMsgs() {
            return this.$store.state.noMoreHistoryMsgs;
        }
    },
    created() {
        // this.$nextTick(() => {
        //     this.stickyOrEnd();
        // });
        // this.getLocalMsgs();
    },
    mounted() {},
    watch: {
        account(val) {
            // this.$nextTick(() => {
            // this.stickyOrEnd();
            // });
            // setTimeout(()=>{
            //     this.stickyOrEnd();
            // },500)
            this.isStickyOrEnd = true;
            this.getTeamMembers();
            this.hideEmoji();
            console.log(val);
            // this.input = val;
        },
        sessionId(val) {
            console.log(val);
            // this.updateLocalMsgDone();
            // this.getLocalMsgs();
        }
    },
    methods: {
        imgPreview(url) {
            console.log("1111");
            this.imgModel = true;
            this.previewUrl = url;
        },
        stickyOrEnd() {
            // console.log(1111);
            // console.log(this.$refs.chatInfo);
            // console.log(scrollHeight);
            this.isStickyOrEnd =
                this.$store.state.currSessionId === null
                    ? true
                    : this.isStickyOrEnd;

            if (this.isStickyOrEnd) {
                setTimeout(() => {
                    let scrollHeight = this.$refs.chatInfo.scrollHeight;
                    this.$refs.chatInfo.scrollTop = scrollHeight;
                }, 100);
            }
            setTimeout(() => {
                this.isStickyOrEnd = false;
            }, 500);
            // if (this.$refs.chatInfo.scrollTop > 0) {
            //     this.$refs.chatInfo.scrollTop = 0;
            // } else {
            //     this.$refs.chatInfo.scrollTop = scrollHeight;
            // }
        },
        getTeamMembers() {
            let scene = /^team/.test(this.sessionId) ? "team" : "p2p";
            console.log(scene)
            if (scene === "team") {
                this.$store.dispatch("getTeamMembers", this.account);
            }
        },
        sendMsg(event) {
            // console.log(event);
            if (event.keyCode === 13) {
                if (event.preventDefault) {
                    event.preventDefault();
                } else {
                    event.returnValue = false;
                }
                // this.input.
                if (this.input === "") {
                    this.$Message.destroy();
                    this.$Message.error("不能发送空白消息");
                    return;
                }
                // console.log(this.input);
                // console.log(this.randomStr(4));
                // console.log(tea.Tea.encrypt(this.input, config.teaKey));
                let scene = /^team/.test(this.sessionId) ? "team" : "p2p";
                // this.scene = /^team/.test(this.sessionId) ? "team" : "p2p";
                let str = tea.xxtea_encrypt(this.input, config.teaKey);
                console.log("192", str);
                // console.log(tea.xxtea_decrypt(str, config.teaKey));
                // console.log(this.input.match(/@[^\s@$]+/g));
                // console.log(tea,config.teaKey)
                this.$store.dispatch("sendMsg", {
                    type: "text",
                    scene: scene,
                    to: this.account,
                    text: str
                    // needMsgReceipt: true
                });
                this.isStickyOrEnd = true;
                this.stickyOrEnd();
                this.input = "";
            }
        },
        sendFileMsg() {
            // 文件消息
            // if (this.invalid) {
            //     this.$toast(this.invalidHint);
            //     return;
            // }
            let scene = /^team/.test(this.sessionId) ? "team" : "p2p";
            let ipt = this.$refs.fileToSent;
            if (ipt.value) {
                this.$store.dispatch("sendFileMsg", {
                    scene: scene,
                    to: this.account,
                    fileInput: ipt
                });
            }
            this.isStickyOrEnd = true;
            this.stickyOrEnd();
        },
        readMoreHistoryMsgs() {
            this.isStickyOrEnd = false;
            this.$emit("getHistoryMsgs");
        },
        addEmoji(emojiName) {
            console.log(emojiName);
            this.input += emojiName;
            this.hideEmoji();
        },
        hideEmoji() {
            this.isEmojiShown = false;
        },
        showEmoji() {
            this.isEmojiShown = !this.isEmojiShown;
        },
        randomStr(length) {
            let $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789";
            let str = "";
            let maxPos = $chars.length;
            for (let i = 0; i < length; i++) {
                // console.log(i);
                str += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return str;
        }
    },
    components: {
        Emoji,
        ChatItem
    }
};
</script>
<style>
.input_region .ivu-input {
    border-width: 0 !important;
    /* height: 80px; */
    /* max-height: 80px; */
}
.input_region .ivu-input:hover {
    border: 0 !important;
    border-color: #fff;
}
.input_region .ivu-input:focus {
    box-shadow: 0px 0px 0px rgb(255, 255, 255) !important;
}
.m_input_content .ivu-input::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 5px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 5px;
}

.m_input_content .ivu-input::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #409eff;
}

.m_input_content .ivu-input::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    /* // box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2); */
    /* // border-radius: 10px; */
    /* // background: #fff; */
    background: rgba(0, 0, 0, 0);
}
.chat_region >>> .ivu-modal .ivu-modal-content .ivu-modal-body {
    padding: 0 !important;
}
</style>
<style scoped lang="less">
.chat_region {
    position: absolute;
    width: 780px;
    top: 0;
    background: #ededed;
    height: 100%;
    border-left: 1px solid #e2e2e2;
    .chat_info::-webkit-scrollbar {
        /*滚动条整体样式*/
        width: 5px;
        /*高宽分别对应横竖滚动条的尺寸*/
        height: 5px;
    }

    .chat_info::-webkit-scrollbar-thumb {
        /*滚动条里面小方块*/
        border-radius: 10px;
        box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: #409eff;
    }

    .chat_info::-webkit-scrollbar-track {
        /*滚动条里面轨道*/
        // box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        // border-radius: 10px;
        background: rgba(0, 0, 0, 0);
    }
    .logo_box {
        width: 100%;
        height: 100%;
        .logo {
            width: 150px;
            height: 150px;
            background: url("../../assets/images/index/logo@2x.png");
            background-size: 100%, 100%;
        }
    }
    .vertical-center-modal {
        display: flex;
        align-items: center;
        justify-content: center;

        .ivu-modal {
            top: 0;
        }
    }
    .chat_region_header {
        width: 100%;
        height: 75px;
        border-bottom: 1px solid #e2e2e2;
        font-size: 20px;
        line-height: 75px;
    }
    .chat_info {
        width: 100%;
        height: 572px;
        overflow-y: auto;
        overflow-x: hidden;
        padding: 28px;
        border-top: 1px solid #ddd;
        box-sizing: border-box;
        background: #ededed;
        .read_more {
            cursor: pointer;
        }
    }
    .input_region {
        width: 760px;
        max-height: 140px;
        padding: 22px;
        box-sizing: border-box;
        background: #fff;
        border-radius: 10px;
        margin: 0 auto;
        position: relative;
        .emoji_content {
            width: 600px;
            background: #fff;
            position: absolute;
            border-radius: 10px;
            left: 0;
            top: 13px;
            z-index: 10;
        }
        .emoji_icon {
            width: 23px;
            height: 23px;
            margin-right: 20px;
            background: url("../../assets/images/index/icon_happy.png");
            background-size: 100%, 100%;
        }
        .files_icon {
            width: 21px;
            height: 17px;
            background: url("../../assets/images/index/icon_folder.png");
            background-size: 100%, 100%;
            input {
                width: 100%;
                height: 100%;
                opacity: 0;
            }
        }
        .m_input {
            margin-bottom: 5px;
            margin-top: 10px;
            // height: 80px;
        }
        .util {
            font-size: 22px;
            text-align: left;
        }
    }
}
</style>
